26. Exercise: Add LiveData Data Binding
ANDK L5 47 LiveData And Databinding SC V4
Now it’s your turn to complete this exercise yourself.
In this step, you'll use LiveData to auto-magically update your layout via data binding. This will allow you to remove all of your observation lambdas for simple UI updates.
1. For score_text and word_text use the LiveData from GameViewModel to set the text attribute:
Open up the game_fragment layout. You can use the word LiveData to set the text for the word_text and score_text TextViews. For example, for word_text:
android:text="@{@string/quote_format(gameViewModel.word)}"
Notice we used quote_format from the string resource to add quotes to each word.
Do the same for score_text using the score_format from the string resources.
2. Call binding.setLifecycleOwner to make the data binding lifecycle aware:
Open GameFragment. To make your data binding lifecycle aware and to have it play nicely with LiveData, you need to call binding.setLifecycleOwner. You must pass in this -- which refers to GameFragment. This looks like:
binding.setLifecycleOwner(this)
3. Remove the score and word observers:
Note that we'll fix the currentTime observation in the next exercise. Once you've removed the score and word observers, you should be able to run your app and see that the score and word text still updates.
Now it's time to update the Score screen.
4. Use the LiveData from GameViewModel to set the score_text text attribute:
This is very similar to what you just did with word_text and score_text. Repeat in score_fragment.xml. Note that since score is a an Int, you'll need to use String.valueOf() in your binding expression to convert the Int to a String.
5. Call binding.setLifecycleOwner and remove the score observer.
Repeat steps 2 and 3 in the ScoreFragment code. Run your app again to make sure it compiles and runs.
If you want to start at this step, you can download this exercise code from: Step.09-Exercise-Add-LiveData-Data-Binding.
You will find plenty of //TODO comments to help you complete this exercise, and if you get stuck go back and watch the video again.
Once you’re done, you can check your solution against the solution we’ve provided here Step.09-Solution-Add-LiveData-Data-Binding or using this git diff.
Task Description:
Check the steps below as you implement them to complete this exercise.
Task Feedback:
Great work! Almost done! You can check your solution against the solution we’ve provided here Step.09-Solution-Add-LiveData-Data-Binding or using this git diff.